/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace GearBlog.Web.Controllers
{
	using System.Drawing;
	using System.Drawing.Imaging;
	using GearBlog.Web.Services;

	public class ImageController:ExtendedControllerBase
	{
		public void GetThumb(string path, int width, int height, bool orgSize)
		{
			string fileName = Context.Server.MapPath(path);
			Bitmap srcBitmap = (Bitmap)Bitmap.FromFile(fileName);

			Bitmap thumbBitmap;
			if (!orgSize)
			{
				thumbBitmap = new Bitmap(width, height);

				Graphics g = Graphics.FromImage(thumbBitmap);
				g.FillRectangle(new SolidBrush(Color.White), new Rectangle(new Point(0, 0), thumbBitmap.Size));

				g.DrawImage(srcBitmap, PositionImage(thumbBitmap.Size, ToThumbSize(srcBitmap.Size, thumbBitmap.Size)));
			}
			else
				thumbBitmap = srcBitmap;

			PropertyBag["actualFilename"] = fileName;
			Context.Response.Clear();
			Context.Response.ContentType = "image/jpeg";
			thumbBitmap.Save(Context.Response.OutputStream, ImageFormat.Jpeg);

			CancelView();
		}
		public void GetThumbFromStore(string storageKey, string fileTitle, int width, int height, bool orgSize)
		{
			IFileStorageService storageService = ServiceContainer.Resolve<IFileStorageService>();
			GetThumb(storageService.GetUrl(storageKey, Context, fileTitle), width, height, orgSize);
		}
		private static Size ToThumbSize(Size orgSize, Size frameSize)
		{
			float heightRatio = Convert.ToSingle(orgSize.Height / frameSize.Height);
			float widthRatio = Convert.ToSingle(orgSize.Width / frameSize.Width);
			float ratio = 0;
			if (heightRatio <= 1 && widthRatio <= 1)
				ratio = 1;
			else ratio = heightRatio > widthRatio ? heightRatio : widthRatio;

			return new Size(Convert.ToInt32(orgSize.Width / ratio), Convert.ToInt32(orgSize.Height / ratio));
		}

		private static Rectangle PositionImage(Size frameSize, Size imageSize)
		{
			Point point = new Point((frameSize.Width - imageSize.Width) / 2, (frameSize.Height - imageSize.Height) / 2);
			return new Rectangle(point, imageSize);
		}
	}
}
